package com.yixuan.mt.core.handler;

import com.yixuan.mt.common.local.buckets.BucketsMeta;
import com.yixuan.mt.common.constant.PathConstant;
import com.yixuan.mt.common.local.objects.ObjectsMeta;
import com.yixuan.mt.common.service.ObjectsService;
import com.yixuan.mt.common.service.impl.ObjectsServiceImpl;
import com.yixuan.mt.core.response.FixedResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Component
public class PostFileController extends AbstractController {

    @Autowired
    private ObjectsService objectsService;

    /**
     * 冗余待优化
     */
    @Override
    void handle(ChannelHandlerContext ctx, HttpRequest httpRequest, HttpContent httpContent) throws IOException {

        File file = new File(PathConstant.FILE_RESOURCE_PATH_PREFIX_MYSQL + httpRequest.uri() + httpRequest.uri().substring(httpRequest.uri().lastIndexOf("/")));
        if (httpRequest.headers().getInt("responseState") == 0) {
            if (file.exists()) {
                FixedResponse.sendFileAlreadyExistsResponse(ctx);
                return;
            }
            // 创建文件的路径的目录
            File parentFile = file.getParentFile();
            if (!parentFile.exists() && !file.getParentFile().mkdirs()) {
                FixedResponse.sendInternalServerErrorResponse(ctx);
                ctx.close();
                return;
            }
            httpRequest.headers().set("responseState", 1);
        }
        // 写入文件
        FileOutputStream fo = new FileOutputStream(file, true);
        FileChannel fc = fo.getChannel();
        int n = httpContent.content().readableBytes();
        ByteBuffer byteBuffer = httpContent.content().nioBuffer(0, n);
        try (fo; fc) {
            while (byteBuffer.hasRemaining()) {
                fc.write(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (httpContent instanceof LastHttpContent) {
            try {
                objectsService.postObjects(httpRequest.uri(), file);
            } catch (Exception e) {
                file.delete();
                FixedResponse.sendInternalServerErrorResponse(ctx);
            }
            // 返回响应
            FixedResponse.sendOkResponse(ctx);
        }
    }
}
